package scatter.portrait.rest.user.scheduler.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.StopWatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import scatter.portrait.pojo.user.po.PortraitUser;
import scatter.portrait.rest.user.service.IPortraitUserService;

import java.util.List;

/**
 * <p>
 * 用户同步模版实现类
 * </p>
 *
 * @author yangwei
 * @since 2021-09-29 13:47
 */
@Slf4j
public abstract class AbstractPortraitUserSynchronizeJob implements IPortraitUserSynchronizeJob {

	public static int pageNoStart = 1;
	public static int pageSize = 100;

	@Autowired
	private IPortraitUserService iPortraitUserService;

	@Override
	public void synchronizeAll() {
		log.info("用户推荐全量用户同步开始");
		StopWatch stopWatch = StopWatch.create("用户推荐全量用户同步");
		stopWatch.start();

		int pageNo = pageNoStart;
		int totalCount = 0;
		List<PortraitUser> recdUsers = fetchAllPortraitUsers(pageNo, pageSize);
		while (CollectionUtil.isNotEmpty(recdUsers)){

			boolean b = iPortraitUserService.saveOrUpdateBatchByUniqueColumn(recdUsers,PortraitUser::getUserId);
			if (b) {
				totalCount += recdUsers.size();
			}else {
				log.warn("用户推荐全量用户同步 保存失败，pageNo={}",pageNo);
			}
			// 下一轮循环
			recdUsers = fetchAllPortraitUsers(++pageNo, pageSize);
		}


		stopWatch.stop();
		log.info("用户推荐全量用户同步结束,处理总条数={},耗时={}ms",totalCount,stopWatch.getTotalTimeMillis());

	}

	/**
	 * 分页获取
	 * @param pageNo
	 * @param pageSize
	 * @return 返回空代码已经没有数据
	 */
	public abstract List<PortraitUser> fetchAllPortraitUsers(int pageNo, int pageSize);

	@Override
	public void synchronizeIncrement() {
		log.info("用户推荐增量用户同步开始");
		StopWatch stopWatch = StopWatch.create("用户推荐增量用户同步");
		stopWatch.start();

		int pageNo = pageNoStart;
		int totalCount = 0;
		List<PortraitUser> recdUsers = fetchIncrementPortraitUsers(pageNo, pageSize);
		while (CollectionUtil.isNotEmpty(recdUsers)){

			boolean b = iPortraitUserService.saveOrUpdateBatchByUniqueColumn(recdUsers,PortraitUser::getUserId);
			if (b) {
				totalCount += recdUsers.size();
			}else {
				log.warn("用户推荐增量用户同步 保存失败，pageNo={}",pageNo);
			}
			// 下一轮循环
			recdUsers = fetchIncrementPortraitUsers(++pageNo, pageSize);
		}


		stopWatch.stop();
		log.info("用户推荐增量用户同步结束,耗时={}ms",stopWatch.getTotalTimeMillis());

	}

	/**
	 * 增量用户获取
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	public abstract List<PortraitUser> fetchIncrementPortraitUsers(int pageNo,int pageSize);

}
